package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
)

// 1、接收客户端 request，并将 request 中带的 header 写入 response header

func rootHandler2(w http.ResponseWriter, r *http.Request) {
	fmt.Println("enter rootHandler2")

	// 获取请求头
	fmt.Printf("%s\n",r.Header)
	// 将请求响应头写入请求体
	for k,v :=range r.Header{
		fmt.Println(r.Header.Get(k),v)
		io.WriteString(w, fmt.Sprintf("%s=%s\n", k, v))
	}
	}

// 2、读取当前系统的环境变量中的 VERSION 配置，并写入 response header
func getEnvHandler(w http.ResponseWriter,r *http.Request)  {
	fmt.Println("enter getEnvHandler")
	Version :=os.Getenv("versions")
	fmt.Println(Version)
	fmt.Println("==============")

}




// 4、访问 localhost/healthz 时，应返回200

func healthHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Println("enter healthHandler")
	u,_:=url.Parse("http://0.0.0.0:8089/healthz")
	q :=u.Query()
	u.RawQuery=q.Encode()
	res,err:=http.Get(u.String())
	if err !=nil{
		fmt.Println(0)
		return
	}
	resCode :=res.StatusCode
	res.Body.Close()
	if err !=nil{
		fmt.Println("0")
		return
	}
	//fmt.Printf("%d\r\n",resCode)
	fmt.Println(resCode,"=============")

	fmt.Fprintf(w,"%d\n",resCode)
}

func main() {

	http.HandleFunc("/", rootHandler2)
	http.HandleFunc("/getEnv", getEnvHandler)
	http.HandleFunc("/healthz", healthHandler)

	log.Fatal(http.ListenAndServe("0.0.0.0:8089", nil))

}